package diona;

import diona.dao.SharedFileDao;
import diona.dao.SharedItem;
import org.apache.commons.io.FileUtils;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * User: anton
 * Date: 20.02.11 15:19
 */
public class ShareHotKeyListener extends HotKeyListener
{
    private static Logger LOG = LoggerFactory.getLogger(ShareHotKeyListener.class);

    private final Notifier notifier;
    private final SharedFileDao fileDao;

    public ShareHotKeyListener(Notifier notifier, SharedFileDao fileDao)
    {
        this.notifier = notifier;
        this.fileDao = fileDao;
    }

    protected void onHotKey()
    {
        new Thread(new Runnable()
        {
            public void run()
            {
                process();
            }
        }).start();
    }

    private void process()
    {
        try {
            String groupId = UUID.randomUUID().toString();
            for (SharedItem item : fileDao.getNotSentItems()) {
                shareImage(item.getPath(), groupId);
                fileDao.markSent(item.getId());
            }
        } catch (Exception e) {
            LOG.error("Error while hot key processing", e);
        }
    }

    private void shareImage(String path, String groupId) throws IOException
    {
        LOG.debug("Image found. Processing started.");

        sendImage(FileUtils.readFileToByteArray(new File(path)), groupId);
    }

    private void sendImage(byte[] bytes, String groupId) throws IOException
    {
        DefaultHttpClient client = new DefaultHttpClient();
        HttpHost host = new HttpHost("localhost", 8080, "http");
        client.getCredentialsProvider().setCredentials(new AuthScope(host.getHostName(), host.getPort()),
                new UsernamePasswordCredentials("a.v.safonov@gmail.com", "qwerty"));
        HttpPut put = new HttpPut("/api/images/add?groupId=" + groupId);
        put.setEntity(new ByteArrayEntity(bytes));

        LOG.debug("Sending image of size {}B...", bytes.length);
        client.execute(host, put);
        LOG.debug("Image sent");

        notifier.showMessage(String.format("Image of size %dB sent.", bytes.length));
    }

    public HotKeyEventType getEventType()
    {
        return HotKeyEventType.SHARE;
    }
}
